//表单提交成功后刷新父级页面,关闭本弹窗
function submitSuccess() {
    parent.reload ? parent.reload() : parent.location.reload();//这里调用的是父页面的reload方法
    setTimeout(function () {
        parent.layer.close(parent.layer.getFrameIndex(window.name));
    }, 1000);
}

//打开图片预览
function openimgs(that) {
    return layer.open({
        type: 1,
        title: false,
        closeBtn: 0,
        area: ['auto'],
        skin: 'layui-layer-nobg', //没有背景色
        shadeClose: true,
        content: '<img  src="' + that.getAttribute('src') + '">'
    });

}

//把10位时间戳格式化
function formatDate(datetime, field) {
    if (datetime === 0||datetime === ''||datetime === null||typeof datetime === "undefined") return '无';

    var date = new Date(datetime * 1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
    var year = date.getFullYear(),
        month = ("0" + (date.getMonth() + 1)).slice(-2),
        sdate = ("0" + date.getDate()).slice(-2),
        hour = ("0" + date.getHours()).slice(-2),
        minute = ("0" + date.getMinutes()).slice(-2),
        second = ("0" + date.getSeconds()).slice(-2);
    // 拼接
    var result = year + "-" + month + "-" + sdate + " " + hour + ":" + minute + ":" + second;
    // 返回

    if (field) {
        layui.use(['jquery'], function () {
            layui.jquery('#' + field).attr('value', result);
        })
    } else return result;
}

/**
 * 把逗号拼接的多图url转换成可点击查看 可删除的HTML代码,供crud生成的index.html中的table行内显示
 * @param urls
 * @returns {string}
 */
function getImagesHtmlForIndex(urls) {
    var imagesHtml = '';
    if (urls) {
        urlArr = urls.split(",");
        urlArr.forEach(v => {
            imagesHtml += "\n" + "                    <img style=\"cursor: pointer;width: 28px;height: 28px\" onclick=\"openimgs(this)\" src=\"" + v + "\">";
        });
    }
    return imagesHtml;
}

/**
 * 把逗号拼接的多图url转换成可点击查看 可删除的HTML代码,供crud生成的index.html中的table行内显示
 * @param urls
 * @returns {string}
 */
function getImagesHtmlForEdit(urls, id_name, inputname) {
    layui.use(['layer'], function () {
        var layer = layui.layer;
        //开启loading
        var loading = layer.load();

        var type = 'image';
        if (typeof inputname === "undefined") {
            inputname = id_name;
        }
        var imagesHtml = '';
        if (urls) {
            urlArr = urls.split(",");
            urlArr.forEach(v => {
                var div_id = uuid();
                imagesHtml += '                                    <div style="display: flex;flex-direction: column;width: 90px;height: 120px" id="' + div_id + '">' +
                    '                                        <img class="layui-upload-img" src="' + v + '" style="width: 80px;height: 80px" onclick="openimgs(this)">' +
                    '                                        <button style="width: 80px;height: 30px" type="button" class="layui-btn layui-btn-sm layui-btn-danger" onclick="delDiv(\'' + div_id + '\',\'' + inputname + '\',\'' + id_name + '\',\'' + type + '\')">' +
                    '                                            <i class="layui-icon">&#xe640;</i>' +
                    '                                        </button>' +
                    '                                    </div>';
            });
            layui.use(['jquery'], function () {
                layui.jquery('#' + id_name + 'Preview').html(imagesHtml);
            })
        }else{
            layui.use(['jquery'], function () {
                layui.jquery('#' + id_name + 'Preview').html('');
            })
        }

        //把路径渲染到input中
        delDiv('', inputname, id_name, type);

        //关闭loading
        layer.close(loading);
    })
}


/**
 * 把逗号拼接的多视频url转换成可点击查看 可删除的HTML代码,供crud生成的index.html中的table行内显示
 * @param urls
 * @returns {string}
 */
function getVideoHtmlForEdit(urls, id_name, inputname) {
    layui.use(['layer'], function () {
        var layer = layui.layer;
        //开启loading
        var loading = layer.load();

        var type = 'video';
        if (typeof inputname === "undefined") {
            inputname = id_name;
        }
        var imagesHtml = '';
        if (urls) {
            urlArr = urls.split(",");
            urlArr.forEach(v => {
                var div_id = uuid();
                imagesHtml += '                                    <div style="display: flex;flex-direction: column;width: 210px;height: 230px" id="' + div_id + '">' +
                    '                                        <video class="layui-upload-img" src="' + v + '" hight="200" width = "200" style="height: 200px" controls="controls"></video>' +
                    '                                        <button style="width: 200px;height: 30px" type="button" class="layui-btn layui-btn-sm layui-btn-danger" onclick="delDiv(\'' + div_id + '\',\'' + inputname + '\',\'' + id_name + '\',\'' + type + '\')">' +
                    '                                            <i class="layui-icon">&#xe640;</i>' +
                    '                                        </button>' +
                    '                                    </div>';
            });
            layui.use(['jquery'], function () {
                layui.jquery('#' + id_name + 'Preview').html(imagesHtml);
            })
        }else{
            layui.use(['jquery'], function () {
                layui.jquery('#' + id_name + 'Preview').html('');
            })
        }
        //把路径渲染到input中
        delDiv('', inputname, id_name, type);

        //关闭loading
        layer.close(loading);
    })
}


/**
 * 上传方法
 * @param upload layui上传对象
 * @param id_name 节点id名
 * @param type  单图image 多图images
 * @param inputname  提交表单name 默认与节点id同名
 * @returns {string}
 */
function bw_upload(upload, id_name, type, inputname, data) {
    //type默认值
    if (typeof type === "undefined") {
        type = 'image';
    }
    //type默认值
    if (typeof inputname === "undefined") {
        inputname = id_name;
    }
    //data默认值
    if (typeof data === "undefined") {
        data = {};
    }

    //上传接口
    var upload_url = "/manage/publicCommon/upload";
    //指定允许上传时校验的文件类型，可选值有：images（图片）、file（所有文件）、video（视频）、audio（音频）
    var accept = 'images';
    //规定打开文件选择框时，筛选出的文件类型，值为用逗号隔开的 MIME 类型列表。
    // 如：acceptMime: 'image/*'（只显示图片文件）
    // acceptMime: 'image/jpg, image/png'（只显示 jpg 和 png 文件）
    var acceptMime = 'image/*';
    var exts = 'jpg|png|gif|bmp|jpeg';

    //根据上传类型区分不同url函数
    switch (type) {
        case 'image':  //单图
        case 'images':  //多图
            break;
        case 'video':  //单视频
        case 'videos':  //多视频
            accept = 'video';
            acceptMime = 'video/mp4';
            exts = 'mp4';
            break;
        case 'file':  //单文件
        case 'files':  //多文件
            accept = 'file';
            acceptMime = 'zip,rar,7z,pem,crt';//限制
            exts = 'zip|rar|7z|pem|crt';
            break;
    }
    //loading变量
    var loading;
    var uploadInst = upload.render({
        elem: '#' + id_name
        , url: upload_url
        , accept: accept//允许上传的文件类型
        , acceptMime: acceptMime//允许上传的文件类型
        , exts: exts//允许上传的文件类型
        ,data: data
        , before: function (res) {
            //开启loading
            loading = layer.load();
        }
        , done: function (res) {
            if (res.data.errcode === 0) {
                var div_id = uuid();

                switch (type) {
                    case 'image':  //单图
                        //渲染图片
                        $('#' + id_name + 'Preview').html('                                    <div style="display: flex;flex-direction: column;width: 90px;height: 120px" id="' + div_id + '">' +
                            '                                        <img class="layui-upload-img" src="' + res.data.data.src + '" onclick="openimgs(this)"  style="width: 80px;height: 80px">' +
                            '                                        <button style="width: 80px;height: 30px" type="button" class="layui-btn layui-btn-sm layui-btn-danger" onclick="delDiv(\'' + div_id + '\',\'' + inputname + '\',\'' + id_name + '\',\'' + type + '\')">' +
                            '                                            <i class="layui-icon">&#xe640;</i>' +
                            '                                        </button>' +
                            '                                    </div>');
                        break;
                    case 'images':  //多图
                        //渲染图片
                        $('#' + id_name + 'Preview').append('                                    <div style="display: flex;flex-direction: column;width: 90px;height: 120px" id="' + div_id + '">' +
                            '                                        <img class="layui-upload-img" src="' + res.data.data.src + '" onclick="openimgs(this)"  style="width: 80px;height: 80px">' +
                            '                                        <button style="width: 80px;height: 30px" type="button" class="layui-btn layui-btn-sm layui-btn-danger" onclick="delDiv(\'' + div_id + '\',\'' + inputname + '\',\'' + id_name + '\',\'' + type + '\')">' +
                            '                                            <i class="layui-icon">&#xe640;</i>' +
                            '                                        </button>' +
                            '                                    </div>');
                        break;
                    case 'video':  //单视频
                        //渲染
                        $('#' + id_name + 'Preview').html('                                    <div style="display: flex;flex-direction: column;width: 210px;height: 230px" id="' + div_id + '">' +
                            '                                        <video class="layui-upload-img" src="' + res.data.data.src + '"  hight="200" width = "200" style="height: 200px" controls="controls" ></video>' +
                            '                                        <button style="width:200px;height: 30px" type="button" class="layui-btn layui-btn-sm layui-btn-danger" onclick="delDiv(\'' + div_id + '\',\'' + inputname + '\',\'' + id_name + '\',\'' + type + '\')">' +
                            '                                            <i class="layui-icon">&#xe640;</i>' +
                            '                                        </button>' +
                            '                                    </div>');
                        break;
                    case 'videos':  //多视频
                        //渲染
                        $('#' + id_name + 'Preview').append('                                    <div style="display: flex;flex-direction: column;width: 210px;height: 230px" id="' + div_id + '">' +
                            '                                        <video class="layui-upload-img" src="' + res.data.data.src + '"  hight="200" width = "200" style="height: 200px" controls="controls"></video>' +
                            '                                        <button style="width:200px;height: 30px" type="button" class="layui-btn layui-btn-sm layui-btn-danger" onclick="delDiv(\'' + div_id + '\',\'' + inputname + '\',\'' + id_name + '\',\'' + type + '\')">' +
                            '                                            <i class="layui-icon">&#xe640;</i>' +
                            '                                        </button>' +
                            '                                    </div>');
                        break;
                    case 'file':  //单文件
                        //渲染图片
                        $('#' + id_name + 'Preview').html('                                    <div style="display: flex;flex-direction: column;width: 90px;height: 120px" id="' + div_id + '">' +
                            '                                        <div class="layui-bg-blue" src="' + res.data.data.src + '" style="width: 80px;height: 80px">' + res.data.data.src + '</div>' +
                            '                                        <button style="width: 80px;height: 30px" type="button" class="layui-btn layui-btn-sm layui-btn-danger" onclick="delDiv(\'' + div_id + '\',\'' + inputname + '\',\'' + id_name + '\',\'' + type + '\')">' +
                            '                                            <i class="layui-icon">&#xe640;</i>' +
                            '                                        </button>' +
                            '                                    </div>');
                        //把url放入表单元素内
                        $("[name='" + inputname + "']").attr('value', res.data.data.src);
                        break;
                    case 'files':  //多文件
                        //渲染
                        $('#' + id_name + 'Preview').append('                                    <div style="display: flex;flex-direction: column;width: 90px;height: 120px" id="' + div_id + '">' +
                            '                                        <div class="layui-bg-blue" src="' + res.data.data.src + '" style="width: 80px;height: 80px">' + res.data.data.src + '</div>' +
                            '                                        <button style="width: 80px;height: 30px" type="button" class="layui-btn layui-btn-sm layui-btn-danger" onclick="delDiv(\'' + div_id + '\',\'' + inputname + '\',\'' + id_name + '\',\'' + type + '\')">' +
                            '                                            <i class="layui-icon">&#xe640;</i>' +
                            '                                        </button>' +
                            '                                    </div>');
                        break;
                }

                //把图片路径渲染到input中
                delDiv('', inputname, id_name, type);

                //关闭loading
                layer.close(loading);
                return layer.msg('上传成功', {icon: 1});
            } else {
                //关闭loading
                layer.close(loading);
                return layer.msg(res.msg, {icon: 2});
            }
        }
        , error: function () {
            //关闭loading
            layer.close(loading);
            return layer.msg('上传失败', {icon: 2});
        }
    });

    return uploadInst;

}







/**
 * 删除div,并给input重新赋值
 * @param div_id
 * @param input_name
 * @param id_name
 * @param type
 */
function delDiv(div_id, input_name, id_name, type) {
    console.log('上传赋值'+div_id,input_name,id_name,type);
    layui.use(['jquery'], function () {
        //删除div
        if (div_id) layui.jquery('div#' + div_id).remove();

        //id_name默认值
        if (typeof id_name === "undefined") {
            id_name = input_name;
        }
        var tab_name;
        if (typeof type === "undefined") {
            tab_name = 'image';
        }

        switch (type) {
            case 'image':  //单图
            case 'images':  //多图
                tab_name = "img";
                break;
            case 'video':  //单视频
            case 'videos':  //多视频
                tab_name = "video";
                break;
            case 'file':  //单文件
            case 'files':  //多文件
                tab_name = "div";
                break;
        }

        var urls = '';
        layui.jquery("#" + id_name + "Preview " + tab_name + "").each(function () {
            var img_url = layui.jquery(this).attr("src");
            if (!urls) urls = img_url;
            else urls = urls + ',' + img_url;
        });

        //把图片url放入表单元素内
        layui.jquery("[name='" + input_name + "']").attr('value', urls);
    })
}

/**
 * uuid生成
 */
function uuid() {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "-";

    var uuid = 'mn'+s.join("");
    return uuid;
}
function isEmpty(a){
    /* 检验空字符串 */
    if (a === "") return true;
    /* 检验字符串类型的null */
    if (a === "null") return true;
    /* 检验字符串类型的 undefined	*/
    if (a === "undefined") return true;
    /* 检验 undefined 和 null */
    if (!a && a !== 0 && a !=="") return true;
    /* 检验空数组	*/
    if (Array.prototype.isPrototypeOf(a) && a.length === 0 ) return true;
    /* 检验空对象  */
    if (Object.prototype.isPrototypeOf(a) && Object.keys(a).length === 0 ) return true;
    return false;
}

/**
 * 百度富文本编辑器 富文本转义为可显示的内容
 * @param str
 * @param field
 */
function htmlDecode(str, field) {
    console.log(str);
    // var temp = document.createElement("div");
    // temp.innerHTML = str;
    // var output = temp.innerText || temp.textContent;
    //
    // var temp2 = document.createElement("div");
    // temp2.innerHTML = output;
    // var output2 = temp2.innerText || temp2.textContent;
    UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
    UE.Editor.prototype.getActionUrl = function(action) {
        if (action == 'uploadimage' || action == 'uploadscrawl' || action == 'uploadimage') {
            return CONFIG.DOMAIN + '/manage/publicCommon/uploadUeditor';
        } else if (action == 'uploadvideo') {
            return CONFIG.DOMAIN + '/manage/publicCommon/uploadUeditor';
        } else {
            return this._bkGetActionUrl.call(this, action);
        }
    }
    var ue = UE.getEditor(field);
    ue.ready(function () {
        ue.setContent(HTMLDecode(str));
    });
}

/**
 *  html反转移
 * @param text
 * @returns {string}
 * @constructor
 */
function HTMLDecode(text)
{
    var temp = document.createElement("div");
    temp.innerHTML = text;
    var output = temp.innerText || temp.textContent;
    temp = null;
    return output;
}


/**
 * param 将要转为URL参数字符串的对象
 * key URL参数字符串的前缀
 * encode true/false 是否进行URL编码,默认为true
 *
 * return URL参数字符串
 */
var urlEncode = function (param, key, encode) {
    if(param==null) return '';
    var paramStr = '';
    var t = typeof (param);
    if (t == 'string' || t == 'number' || t == 'boolean') {
        paramStr += '&' + key + '=' + ((encode==null||encode) ? encodeURIComponent(param) : param);
    } else {
        for (var i in param) {
            var k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i);
            paramStr += urlEncode(param[i], k, encode);
        }
    }
    return paramStr;
};

<!-- index.html的通用方法 -->
//重置所有筛选条件
function resetForm() {
    //将筛选条件全部清空
    document.getElementById("searchForm").reset();

    //调用表格重载
    reload(1);
}

//获取搜索条件
function getWhere() {
    var where = form.val("searchForm");//这里的searchForm是form的lay-filter

    return where;
}

//表格重载
function reload(page) {
    var where = getWhere();//获取搜索条件

    var page_now = $(".layui-laypage-em").next().html(); //当前页码值
    var page_to = page ? page : page_now;

    table.reload('list', {
        where: where, //设定异步数据接口的额外参数
        page: {curr: page_to}//设置页数
    });
}

/**
 * 使用传递过来的where条件渲染form表单
 * @param where js对象
 * @param form_id 表单id
 */
function bwRenderForm(where, form_id){
    if(form_id === undefined) form_id = "searchForm";

    //给表单赋值
    form.val(form_id, where);
}

/**
 * 打开iframe弹出层
 * @param url 弹窗层的url
 * @param title 弹出层标题
 */
function bwOpenIframe(url, title, width, height) {
    if(width === undefined) width = '90%';
    if(height === undefined) height = '90%';

    layui.use(['layer'], function () {
        layui.layer.open({
            title: title,
            type: 2,
            shade: 0.2,
            maxmin: true,
            area: [width, height],
            content: url,
        });
    })
}

/**
 * 富文本编码
 * @param text
 * @returns {string}
 */
function r_text_encode(text)
{
    return window.btoa(window.encodeURIComponent(text))
}

/**
 * 富文本解码
 * @param text
 * @returns {string}
 */
function r_text_decode(text)
{
    return window.decodeURIComponent(window.atob(text))
}
// 自定义高精度浮点数运算
// 对象格式写法
var float_calculator={
    /**
     * 1.记录两个运算数小数点后的位数
     * 2.将其转化为整数类型进行运算
     * 3.移动小数点的位置
     **/
    add:function(arg1,arg2){
        var r1,r2,m;
        try{
            //取小数位长度
            r1=arg1.toString().split(".")[1].length;
            r2=arg2.toString().split(".")[1].length;
        }catch(e){
            r1=0;r2=0;
        }
        m=Math.pow(10,Math.max(r1,r2));		//计算因子

        return (arg1*m+arg2*m)/m;
    },
    minus:function(arg1,arg2){
        return this.add(arg1,-arg2);
    },
    mul:function(arg1,arg2){
        var r1,r2,m;
        try{
            //取小数位长度
            r1=arg1.toString().split(".")[1].length;
            r2=arg2.toString().split(".")[1].length;
        }catch(e){
            r1=0;r2=0;
        }
        m=Math.pow(10,Math.max(r1,r2));		//计算因子

        return (arg1*m)*(arg2*m)/(m*m);
    },
    div:function(arg1,arg2){
        if( arg2 == 0 ) return 0;
        var t1=0,t2=0,r1,r2;
        try{
            t1=arg1.toString().split(".")[1].length;
            t2=arg2.toString().split(".")[1].length;
        }catch(e){}

        with(Math){
            r1=Number(arg1.toString().replace(".",""));
            r2=Number(arg2.toString().replace(".",""));
        }

        return (r1/r2)*Math.pow(10,t2-t1);
    }
};